package org.karelun.rabbit.rcp.editpart;

import java.util.List;

import org.eclipse.draw2d.FreeformLayer;
import org.eclipse.draw2d.FreeformLayout;
import org.eclipse.draw2d.IFigure;
import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.swt.widgets.Display;
import org.karelun.ideaboard.gef.EditPolicy;
import org.karelun.ideaboard.gef.editparts.AbstractGraphicalEditPart;
import org.karelun.rabbit.graph.Diagram;
import org.karelun.rabbit.graph.GraphPackage;
import org.karelun.rabbit.graph.Shape;
import org.karelun.rabbit.rcp.policy.DiagramLayoutEditPolicy;

public class DiagramEditPart extends AbstractGraphicalEditPart implements Adapter{
	
	private Notifier notifier;
	
	public DiagramEditPart(){
	}
	
	@Override
	protected List<Shape> getModelChildren() {
		Diagram diagram=(Diagram)getModel();
		return diagram.getShapes();
	}
	
	@Override
	protected IFigure createFigure() {
		FreeformLayer layer = new FreeformLayer();
		layer.setLayoutManager(new FreeformLayout());
		return layer;
	}

	@Override
	protected void createEditPolicies() {
		installEditPolicy(EditPolicy.LAYOUT_ROLE, new DiagramLayoutEditPolicy());
	}

	@Override
	public void activate() {
		super.activate();
		((Diagram)getModel()).eAdapters().add(this);
	}
	
	@Override
	public void deactivate() {
		((Diagram)getModel()).eAdapters().remove(this);
		super.deactivate();
	}
	
	@Override
	public void notifyChanged(Notification notification) {
		int featureID = notification.getFeatureID(GraphPackage.class);
		switch (featureID) {
		case GraphPackage.DIAGRAM__SHAPES:
			Runnable runnable=new Runnable(){
				public void run() {
					refreshChildren();
				}
			};
			Display.getDefault().asyncExec(runnable);
			break;
		}
	}

	@Override
	public Notifier getTarget() {
		return notifier;
	}

	@Override
	public void setTarget(Notifier newTarget) {
		this.notifier=newTarget;
	}

	@Override
	public boolean isAdapterForType(Object type) {
		return type.equals(getModel().getClass());
	}
}
